package com.wider.servlets;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.UnsupportedEncodingException;



import javax.mail.MessagingException;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.wider.json.JSONException;
import com.wider.json.JSONObject;
import com.wider.servlet.AppletHTML;
import com.wider.servlet.MultipartFormData;

import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.net.InetAddress;
/**
 * Servlet implementation class Servlet
 */
public class Servlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Logger  logger;
	MultipartFormData formdata;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Servlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		System.out.println("123!!!");
		String igotit=request.getParameter("name");
		System.out.println(igotit);
		PrintWriter pnd;
		pnd = response.getWriter();
		pnd.write("uiui");
		pnd.close();
		/*
		String type = request.getParameter("type");

		if(type!=null){
			download(response);
		}
		else{
			InetAddress is = InetAddress.getLocalHost() ;
		
			PrintWriter pnd;
			pnd = response.getWriter();
			AppletHTML applet_html = new AppletHTML();
			applet_html.SetAppletClass("com.wider.applets.AppletV1");
			applet_html.SetAppletCodebase("./applet/");
			applet_html.SetAppletArchive("");
			applet_html.SetAppletSize(1000, 500);
			applet_html.SetParameter("serverIP", is.getHostAddress());
			applet_html.EndOptions();
//			PrintWriter rspndr = response.getWriter();
			pnd.println("<HTML><HEAD><TITLE>Echo webapp</TITLE></HEAD><BODY>");
			//pnd.println("Hello! This is Echo webapp");
			pnd.println(applet_html.toString());
			pnd.println("</BODY></HTML>");
		}
		*/
	}

	public void make_response(Map<Object, Object> params, HttpServletResponse response) throws  IOException, MessagingException {
        try {
            //Retrieve the parameters and construct the params string
            Iterator paramsit = params.entrySet().iterator();
            //Instanciate an MimeMultipart as a container
            MimeMultipart multipart = new MimeMultipart();
            multipart.setSubType("form-data");
            //Iterates each parameter pair
            while (paramsit.hasNext()) {
                //Get the key-value pair from the Iterator
                Map.Entry param = (Map.Entry) paramsit.next();
                Object paramkey = param.getKey();
                Object paramval = URLEncoder.encode(param.getValue().toString(), "utf8");
                //Construct the bodypart according to the type, then attach it to the Multipart
                //If the paramkey is type of File, the paramval will be used as the key of the bodypart
                if (paramkey.getClass().equals(File.class)){
                    File file = (File) paramkey;
                    MimeBodyPart mimebody = new MimeBodyPart();
                    mimebody.setDisposition("file; name=" + (String)paramval);
                    mimebody.attachFile(file);
                    mimebody.setFileName(MimeUtility.encodeText(file.getName(), "utf8", "B"));
                    multipart.addBodyPart(mimebody);
                } else {
                    //Not a file, currently supports SetText only
                    String content = paramval.toString();
                    MimeBodyPart mimebody = new MimeBodyPart();
                    mimebody.setDisposition("form-data; name=" + paramkey);
                    mimebody.setText(content);
                    
                    multipart.addBodyPart(mimebody);
                }
            }
            //Attach the multipart to the connection stream         
            multipart.writeTo(response.getOutputStream());

        }catch (IOException ex) {
            logger.log(Level.WARNING, "IOException occurs while starting the HTTP POST transaction.", ex);
            throw ex;
        }catch (MessagingException ex) {
            logger.log(Level.WARNING, "MessagingException occurs while starting the HTTP POST transaction.", ex);
            throw ex;
        }

    }



 
 
 	public HashMap<Object,Object> pullMap(HttpServletRequest request)throws IOException{
 		HashMap<Object,Object> dataMap=new HashMap();
 		formdata = new MultipartFormData(request);
		Iterator paramit = formdata.getParameterMap().entrySet().iterator();
		while(paramit.hasNext()){
			 Map.Entry<Object, Object> param = (Map.Entry<Object, Object>) paramit.next();
			 Object paramkey = param.getKey();
			 Object paramval = param.getValue();
			 if(paramval.getClass().equals(String.class)){
				 paramval=URLDecoder.decode(param.getValue().toString(), "utf8");
				 //System.out.println("server side is string!");
			 }
			 dataMap.put(paramkey, paramval);
		 }
		return dataMap;
 	}
 	public int pullType(HashMap<Object,Object> inMap){
 		int type=0;
 		type=Integer.parseInt(inMap.get("type").toString());
 		inMap.remove("type");
 		return type;
 	}
 	
 	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("bon!");
		int type=0;
		HashMap<Object,Object> dataMap=new HashMap();
		dataMap=pullMap(request);
		type=pullType(dataMap);
		
		switch(type){
		case 0 :
			type0(response);
			break;
		case 1 :
			type1(response,dataMap);
			break;
		case 2 :
			type2(response,dataMap);
			break;
		case 3 :
			type3(response,dataMap);
			break;
		case 4 :
			type4(response,dataMap);
			break;
		case 5 :
			type5(response,dataMap);
			break;
		default :
			break;
		
		
		}
	}
	//type5 test JSON
	public void type5(HttpServletResponse response,HashMap<Object,Object> inMap) throws UnsupportedEncodingException{
		String json=new String();
		json=inMap.get("json").toString();
		try {
			JSONObject jo =new JSONObject(json);
			JSONObject jo2=new JSONObject(jo.get("obj1").toString());
			System.out.println(jo2.get("child1").toString());
		} catch (JSONException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		HashMap<Object,Object> mapToSend=new HashMap();
		mapToSend.put("over","endend");
		try {
			make_response(mapToSend,response);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
	public void type4(HttpServletResponse response,HashMap<Object,Object> inMap) throws UnsupportedEncodingException{
		HashMap<Object,Object> copyMap =new HashMap(inMap);
		Iterator paramit=copyMap.values().iterator();
		HashMap<Object,Object> mapToSend=new HashMap();
//		while(paramit.hasNext()){
			//Object path[]=new Object[3];
			Vector inPath;
			//inPath=(Vector)paramit.next();

			//System.out.println("Vector success haha " + inPath.get(0).toString()+ inPath.get(1).toString()+ inPath.get(2).toString());
			System.out.println("got you!  " + paramit.next().toString() );
			mapToSend.put("123","123");
//		}
		try {
			make_response(mapToSend,response);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void type3(HttpServletResponse response,HashMap<Object,Object> inMap) throws UnsupportedEncodingException{
		HashMap<Object,Object> copyMap =new HashMap(inMap);
		Iterator paramit=copyMap.values().iterator();
		HashMap<Object,Object> mapToSend=new HashMap();
		while(paramit.hasNext()){
			//Object path[]=new Object[3];
			String inPath=new String();
			inPath=(String)paramit.next();
			System.out.println(inPath);
			String path[]=new String[3];
			path=inPath.split("sss");
			System.out.println(path[0]+" " + path[1]+" "+path[2]);
			//System.out.println((String)paramit.next());
			//(array)path
			//Vector downloadVector=new Vector();
			//System.out.println(path+"    "+path.toString());
			//mapToSend.put(new File(path),"XXX");
			mapToSend.put(new File(path[2]),path[1].replace(":\\\\", "+"));
		}
		try {
			make_response(mapToSend,response);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void type2(HttpServletResponse response,HashMap<Object,Object> inMap){
		Iterator paramit;
		try {
			paramit = formdata.getParameterMap().entrySet().iterator();

        while(paramit.hasNext()){
            Map.Entry<String, Object> param = (Map.Entry<String, Object>) paramit.next();
            String paramkey = URLDecoder.decode(param.getKey().toString(),"utf-8");
            Object paramval = param.getValue();
            System.out.println("Parameter: " + paramkey + " ^:^ " + paramval);
            //System.out.println("HI: " + paramkey.toString().replace("+", "://") );
            if (paramval.getClass().getName() == ArrayList.class.getName()){
                System.out.println("Found ArrayList.");
                ArrayList<String> files = (ArrayList<String>) paramval;
                try {
                    int ret = 0;
                    //System.out.println("key & val"+paramkey.toString()+" "+paramval.toString());
                    System.out.println("cola"+paramval.toString());
                   // ret = formdata.saveFiles(files, "D:/receive");
                    ret = formdata.saveFiles(files,paramkey.toString().replace("+", "://"));
                    System.out.println("Files saved? " + ret);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
		} catch (IOException e1) {e1.printStackTrace();
		}
		inMap.clear();
		inMap.put("over", "end");
		try {
			make_response(inMap,response);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void type1(HttpServletResponse response,HashMap<Object,Object> inMap){
		
		String path=inMap.get("sdf").toString();
		fileTools tools=new fileTools();
		
		//HashMap<Object,Object> outMap=new HashMap(tools.getChild(path));
		//HashMap<Object,Object> outMap=new HashMap();
		//outMap.put(123, 321);
		HashMap<Object,Object> outMap=new HashMap(tools.getChild(path));
		if(outMap.isEmpty())
			outMap.put(-1, "This floder is Empty");
		try{make_response(outMap, response);}catch (Exception e){}
	}
	
	public void type0(HttpServletResponse response){
		File[] Roots = File.listRoots();
		String rootList;
		rootList="{";
		HashMap<Object,Object> rootMap=new HashMap();
		for(int loop=0;loop<Roots.length;loop++){
			rootList=rootList+"'s"+loop+"'"+":"+'"'+Roots[loop]+"\\"+'"';
			if(Roots.length!=loop+1)
				rootList=rootList+",";
			
		}
		rootList=rootList+"}";
		rootMap.put(123, rootList);
        try{make_response(rootMap, response);}catch (Exception e){}
	}
	
    public void upload(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException{
    	int meg;
    	byte fileContent[] = new byte[100];
    	//String uploadPath;
    	try{
    		meg=0;
    		ServletInputStream stream = null;  	
    		FileOutputStream fout;
    		fout=new FileOutputStream("D:\\789.mp3");
    		stream = request.getInputStream();
    		try{
    			while(meg!=-1){
    				meg=stream.read(fileContent);
    				fout.write(fileContent,0,meg);
				}
              stream.close();
              fout.close();
    		}
    		catch(IOException e){}
    	}
    	catch(IOException ioe){throw new ServletException(ioe.getMessage());}
    }
    
    
    
    
    public void download(HttpServletResponse response) throws IOException{
    	FileInputStream fin;
    	ServletOutputStream stream = null;
    	int meg;
    		stream = response.getOutputStream();
    		URL dir = null;
    		URLConnection dirConn = null;
    		dir = new URL("http://140.123.107.145:8080/filejilla/123.txt");
    		dirConn = dir.openConnection();
    		response.setContentType("text/html"); 
    	    try{
    	    	while((meg=dirConn.getInputStream().read())!=-1){
    	    		stream.write(meg);
    	    		System.out.println(meg);
    	    	}
    	    }
    	    catch(IOException e){}
    	stream.close();
    }

    
   
    
    
    
    
}
